package com.manli.wechat.utils.wxpayv3.wxsdk;


import com.alibaba.fastjson.JSON;
import com.manli.wechat.utils.wxpayv3.pojo.WeChatPayV3CallBackUrl;
import com.manli.wechat.utils.wxpayv3.wxsdk.util.PemUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;

public class HttpClientBuilderTest {

//  private static String mchId = "1900009191"; // 商户号
//  private static String mchSerialNo = "1DDE55AD98ED71D6EDD4A4A16996DE7B47773A8C"; // 商户证书序列号

  private static String mchId = "1601420795"; // 商户号
  private static String mchSerialNo = "41438B625799A164EFBD308A43EA9B62C30AF0FC"; // 商户证书序列号

  private static String reqdata = "{"
      + "    \"stock_id\": \"9433645\","
      + "    \"stock_creator_mchid\": \"1900006511\","
      + "    \"out_request_no\": \"20190522_001中文11\","
      + "    \"appid\": \"wxab8acb865bb1637e\""
      + "}";

  // 你的商户私钥
  private static String privateKey = "-----BEGIN PRIVATE KEY-----"
      + "-----END PRIVATE KEY-----";

  // 你的微信支付平台证书
  private static String certificate =  "-----BEGIN CERTIFICATE-----"
      + "-----END CERTIFICATE-----";

  public static void main(String[] args) throws Exception{
    String content = new String(Files.readAllBytes(Paths.get("C:\\Users\\fjc\\Desktop\\1601420795_20200806_cert\\apiclient_key.pem")), "utf-8");
    String content1 = new String(Files.readAllBytes(Paths.get("C:\\Users\\fjc\\Desktop\\1601420795_20200806_cert\\apiclient_cert.pem")), "utf-8");
    String content2 = new String(Files.readAllBytes(Paths.get("C:\\Users\\fjc\\Desktop\\1601420795_20200806_cert\\apiclient_pub.pem")), "utf-8");

    // 你的商户私钥
    PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
            new ByteArrayInputStream(content.getBytes("utf-8")));
    // 你的微信支付平台证书
    X509Certificate wechatpayCertificate = PemUtil.loadCertificate(
            new ByteArrayInputStream(content1.getBytes("utf-8")));

//    PublicKey merchantPubKey = PemUtil.loadPublicKey(
//            new ByteArrayInputStream(content2.getBytes("utf-8")));

    ArrayList<X509Certificate> listCertificates = new ArrayList<>();
    listCertificates.add(wechatpayCertificate);

    CloseableHttpClient httpClient = WechatPayHttpClientBuilder.create()
            .withMerchant(mchId, mchSerialNo, merchantPrivateKey)
            .withWechatpay(listCertificates)
            .build();

    //GET测试成功
    URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/certificates");
    uriBuilder.setParameter("p", "1&2");
    uriBuilder.setParameter("q", "你好");

    HttpGet httpGet = new HttpGet(uriBuilder.build());
    httpGet.addHeader("Accept", "application/json");

    CloseableHttpResponse response1 = httpClient.execute(httpGet);
    System.out.println(response1.getStatusLine().getStatusCode());

      HttpEntity entity1 = response1.getEntity();
      String reStr = EntityUtils.toString(entity1);
    System.out.println(reStr);
      // do something useful with the response body
      // and ensure it is fully consumed
      EntityUtils.consume(entity1);

      response1.close();

    //

    httpClient.close();

    //////////////////POST测试成功
//    HttpPost httpPost = new HttpPost(
//            "https://api.mch.weixin.qq.com/v3/marketing/favor/coupon-stocks");
//
//
//    InputStream stream = new ByteArrayInputStream(reqdata.getBytes("utf-8"));
//    InputStreamEntity reqEntity = new InputStreamEntity(stream);
//    reqEntity.setContentType("application/json");
//    httpPost.setEntity(reqEntity);
//    httpPost.addHeader("Accept", "application/json");
//
//    CloseableHttpResponse response = httpClient.execute(httpPost);
//    try {
//      HttpEntity entity2 = response.getEntity();
//      // do something useful with the response body
//      // and ensure it is fully consumed
//      System.out.println(EntityUtils.toString(entity2));
//      EntityUtils.consume(entity2);
//    } finally {
//      response.close();
//    }
    /////////////////

    ///////////////POST测试成功
    HttpPost httpPost = new HttpPost(
            "https://api.mch.weixin.qq.com/v3/marketing/favor/callbacks");

    WeChatPayV3CallBackUrl weChatPayV3CallBackUrl = new WeChatPayV3CallBackUrl();
    weChatPayV3CallBackUrl.setMchid("1601420795");
    weChatPayV3CallBackUrl.setNotify_url("https://www.manli.com/test/");
    weChatPayV3CallBackUrl.setSwitch1(false);
    String bean = JSON.toJSONString(weChatPayV3CallBackUrl);

    InputStream stream = new ByteArrayInputStream(bean.getBytes("utf-8"));
    InputStreamEntity reqEntity = new InputStreamEntity(stream);
    reqEntity.setContentType("application/json");
    httpPost.setEntity(reqEntity);
    httpPost.addHeader("Accept", "application/json");

    CloseableHttpResponse response = httpClient.execute(httpPost);
    try {
      HttpEntity entity2 = response.getEntity();
      System.out.println(EntityUtils.toString(entity2));
      // do something useful with the response body
      // and ensure it is fully consumed
      EntityUtils.consume(entity2);

    } finally {
      response.close();
    }
    /////////////////

    //返回成功了，就差解密了
    //{"data":[{"effective_time":"2020-08-06T11:17:43+08:00","encrypt_certificate":{"algorithm":"AEAD_AES_256_GCM","associated_data":"certificate","ciphertext":"ykIPkKwzS+NLRd4MZWZVb9wctwdJmBvpXXU/UkEO69QkSRU11MCt7b5GQu07GhexrZx2QiPGboh4bQYKRISCS6CbJj/yd2XteRnvHuyR2w/nAo6kTqSkfs0CUObCnRyXYMcMrkM2x0l2EVaOV5tle9LW3RvdwK4Iq17+qTaz5zRcxwQEHU0xk61BBilDiKCN5uhynaWsocSRnWzhuRiBQfCIOI8T/mhu2BEZkmKvzloz4Op0gluwfJ9tPl3oad7fZAo+aMaurx6+y1qlqHZZ8Ya034O7QhPOaetQZsZfW6BUaRYlCOr808f3b8aopzwhKae/bb34bSnI3OrAfvDFATfaZ82OL0T5r+EtpKIrB0ysukztKugIoG+zS2ExMM11Ha8sdgumbZsk64GPMPnolF9iTiNEp1Jo4GUULa8x6/spPSWuhyBw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7bf+ZSBIUOshFCMZPrqgSgIP9GTZ5bnnDjzdtSXGTDOS0m0wXYXWfT021fhQajUZYJ1P7tHi3fPZPQON3MLhCU1hN9SMyb5CFmTO7RMbZI9lD+RufFjRT+qGjgl4yqGHqdr/3DL9jh40pYDdA4im+IcHeA/ey/r+LqSbX/FtR7SgGmfSsGlVLTQu8gYKOCU4Q5YR3RHdcLjyLypJOhrXLa3TOuGpF9763F2FS2xCi1K3gFxAS+t9mqNESp1GaLacUQ17P5fljIPF9fTZjpu3EEmpBzk7VR8TGQ5MfqOGEHkwyPW7I40sPWcYCu4lGisrpS1DzAemagfLb5T8oVnVf+ehY+Pk1eUmeBU5oGTHw==","nonce":"43d6e9afa2d9"},"expire_time":"2025-08-05T11:17:43+08:00","serial_no":"1B7F7706BA77354D569CCD5DD339D8D40127EB5D"}]}
    //AesUtil的参数返回的json里都有
    //就差服务商后台的v3密钥了。初始化AesUtil了

//    JSONObject jsonObject = JSONObject.parseObject(reStr);
//    String associatedData = jsonObject.getJSONArray("data").getJSONObject(0).getJSONObject("encrypt_certificate").getString("associated_data");
//    String nonce = jsonObject.getJSONArray("data").getJSONObject(0).getJSONObject("encrypt_certificate").getString("nonce");
//    String ciphertext = jsonObject.getJSONArray("data").getJSONObject(0).getJSONObject("encrypt_certificate").getString("ciphertext");
//
//    String v3Key = "aec3c19110123a22520ea1cb4f77706a";
//    AesUtil aesUtil = new AesUtil(v3Key.getBytes());
//    String deStr = aesUtil.decryptToString(associatedData.getBytes(),nonce.getBytes(),ciphertext);
//    System.out.println(deStr);
//
//    String dedeSte = RsaCryptoUtil.decryptOAEP(deStr,merchantPrivateKey);
//    System.out.println(dedeSte);

    ///////////图片上传测试成功
//    uploadImageTest(httpClient);

  }


//  public void getCertificateTest() throws Exception {
//    URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/certificates");
//    uriBuilder.setParameter("p", "1&2");
//    uriBuilder.setParameter("q", "你好");
//
//    HttpGet httpGet = new HttpGet(uriBuilder.build());
//    httpGet.addHeader("Accept", "application/json");
//
//    CloseableHttpResponse response1 = httpClient.execute(httpGet);
//
//    assertEquals(200, response1.getStatusLine().getStatusCode());
//
//    try {
//      HttpEntity entity1 = response1.getEntity();
//      // do something useful with the response body
//      // and ensure it is fully consumed
//      EntityUtils.consume(entity1);
//    } finally {
//      response1.close();
//    }
//  }
//
//
//  public void getCertificatesWithoutCertTest() throws Exception {
//    PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
//        new ByteArrayInputStream(privateKey.getBytes("utf-8")));
//
//    httpClient = WechatPayHttpClientBuilder.create()
//        .withMerchant(mchId, mchSerialNo, merchantPrivateKey)
//        .withValidator(response -> true)
//        .build();
//
//    getCertificateTest();
//  }
//
//
//  public void postNonRepeatableEntityTest() throws IOException {
//    HttpPost httpPost = new HttpPost(
//        "https://api.mch.weixin.qq.com/v3/marketing/favor/users/oHkLxt_htg84TUEbzvlMwQzVDBqo/coupons");
//
//
//    InputStream stream = new ByteArrayInputStream(reqdata.getBytes("utf-8"));
//    InputStreamEntity reqEntity = new InputStreamEntity(stream);
//    reqEntity.setContentType("application/json");
//    httpPost.setEntity(reqEntity);
//    httpPost.addHeader("Accept", "application/json");
//
//    CloseableHttpResponse response = httpClient.execute(httpPost);
//    assertTrue(response.getStatusLine().getStatusCode() != 401);
//    try {
//      HttpEntity entity2 = response.getEntity();
//      // do something useful with the response body
//      // and ensure it is fully consumed
//      EntityUtils.consume(entity2);
//    } finally {
//      response.close();
//    }
//  }
//
//
//  public void postRepeatableEntityTest() throws IOException {
//    HttpPost httpPost = new HttpPost(
//        "https://api.mch.weixin.qq.com/v3/marketing/favor/users/oHkLxt_htg84TUEbzvlMwQzVDBqo/coupons");
//
//    // NOTE: 建议指定charset=utf-8。低于4.4.6版本的HttpCore，不能正确的设置字符集，可能导致签名错误
//    StringEntity reqEntity = new StringEntity(
//        reqdata, ContentType.create("application/json", "utf-8"));
//    httpPost.setEntity(reqEntity);
//    httpPost.addHeader("Accept", "application/json");
//
//    CloseableHttpResponse response = httpClient.execute(httpPost);
//    assertTrue(response.getStatusLine().getStatusCode() != 401);
//    try {
//      HttpEntity entity2 = response.getEntity();
//      // do something useful with the response body
//      // and ensure it is fully consumed
//      EntityUtils.consume(entity2);
//    } finally {
//      response.close();
//    }
//  }

    public static void uploadImageTest(CloseableHttpClient httpClient) throws Exception {
    String filePath = "C:\\Users\\fjc\\Desktop\\20200609171901.png";

    URI uri = new URI("https://api.mch.weixin.qq.com/v3/marketing/favor/media/image-upload");

    File file = new File(filePath);
    try (FileInputStream s1 = new FileInputStream(file)) {
      String sha256 = DigestUtils.sha256Hex(s1);
      try (InputStream s2 = new FileInputStream(file)) {
        WechatPayUploadHttpPost request = new WechatPayUploadHttpPost.Builder(uri)
            .withImage(file.getName(), sha256, s2)
            .build();

        CloseableHttpResponse response1 = httpClient.execute(request);

        try {
          HttpEntity entity1 = response1.getEntity();
          // do something useful with the response body
          // and ensure it is fully consumed
          String s = EntityUtils.toString(entity1);
          System.out.println(s);
        } finally {
          response1.close();
        }
      }
    }
  }
}
